package pers.acp.test.kotlin.base

import com.zaxxer.hikari.HikariDataSource
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter

/**
 * @since JDK 17
 */
open class BaseJpaConfig(private val jpaProperties: JpaProperties, private val hibernateProperties: HibernateProperties) {
    protected fun buildEntityManagerFactory(hikariDataSource: HikariDataSource): LocalContainerEntityManagerFactoryBean {
        val em = LocalContainerEntityManagerFactoryBean()
        em.dataSource = hikariDataSource
        em.setPackagesToScan(
            *hikariDataSource.dataSourceProperties.getProperty("scan-package").split(",".toRegex())
                .dropLastWhile { it.isEmpty() }.toTypedArray()
        )

        val vendorAdapter = HibernateJpaVendorAdapter()
        em.jpaVendorAdapter = vendorAdapter
        em.setJpaPropertyMap(
            hibernateProperties.determineHibernateProperties(
                jpaProperties.properties,
                HibernateSettings()
            )
        )
        return em
    }
}
